/*================================================================
*   文件名称：main.cpp
*   创 建 者：yang qiang
*   创建日期：2019年12月14日
*   版    本：v1.0.0
*   描    述：
*   Copyright (C) 2019 All rights reserved.
*   
* ================================================================*/


#include <iostream>
#include <queue>
#include <vector>
using namespace std;

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int widthOfBinaryTree(TreeNode* root) {
        if(!root){
            return 0;
        }        

        unsigned long long max_width = 1, len = 0;
        TreeNode *p = NULL;
        unsigned long long pos = 0;
        queue<TreeNode *> s;
        queue<unsigned long long> data;
        s.push(root);
        data.push(0);

        while(!s.empty()){
            len = s.size();
            int i = 0;
            while(i < len){
                p = s.front();
                s.pop();

                pos = data.front();
                data.pop();
                if(p->left){
                    data.push(pos*2);
                    s.push(p->left);
                }

                if(p->right){
                    data.push(pos*2+1);
                    s.push(p->right);
                }

                i++;
            }

            if(data.size() >= 2){
                max_width = max(max_width, data.back() - data.front() + 1);
            }
        }

        return max_width;
    }
};